package com.easycar.common.util;

import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.text.TextUtils;
import android.util.Base64;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;


/**
 * 文件管理
 */
public class FileUtil {

    private static HashMap<String, Boolean> mapInitied = new HashMap<>();


    /**
     * 获取光享指南存储的根目录
     * @return
     */
    public  static  String  getEasyDir(){
        return SDCardUtil.SD_PATH_EXTERNAL +File.separator + SDCardUtil.COMPANY;

    }

    /**
     * 在SDcard 目录下 创建对应的目录
     */
    public static void createTmpDir(Context context) {
        String tmpDir = SDCardUtil.SD_PATH_EXTERNAL +File.separator + SDCardUtil.COMPANY;
        FileUtil.makeDir(tmpDir);
    }

    /**
     * 文件是否可以读
     * @param filename  文件名称   基于光享科技根目录
     * @return
     */
    public static boolean fileCanRead(String filename) {
        String tmpDir = SDCardUtil.SD_PATH_EXTERNAL +File.separator + SDCardUtil.COMPANY+File.separator+filename;
        File f = new File(tmpDir);
        return f.canRead();
    }


    /**
     * 创建文件目录
     * @param dirPath    路径
     * @return
     */
    public static boolean makeDir(String dirPath) {
        File file = new File(dirPath);
        if (!file.exists()) {
            return file.mkdirs();
        } else {
            return true;
        }
    }

    /**
     * 拷贝Assets 资源文件到光享根目录
     * @param context  上下文
     * @param sourceFilename  文件名称
     * @throws IOException  异常
     */
    public static  void copyAssetsFile(Context context,String sourceFilename) throws IOException {
        String destFilename = SDCardUtil.SD_PATH_EXTERNAL +File.separator + SDCardUtil.COMPANY+ File.separator + sourceFilename;
        boolean recover = false;
        Boolean existed = mapInitied.get(sourceFilename); // 启动时完全覆盖一次
        if (existed == null || !existed) {
            recover = true;
        }
        FileUtil.copyFromAssets(context.getApplicationContext().getAssets(), sourceFilename, destFilename, recover);
        GLog.e("文件复制成功"+sourceFilename);
    }




    public static void copyFromAssets(AssetManager assets, String source, String dest, boolean isCover)
            throws IOException {
        File file = new File(dest);
        if (isCover || (!isCover && !file.exists())) {
            InputStream is = null;
            FileOutputStream fos = null;
            try {
                is = assets.open(source);
                fos = new FileOutputStream(dest);
                byte[] buffer = new byte[1024];
                int size = 0;
                while ((size = is.read(buffer, 0, 1024)) >= 0) {
                    fos.write(buffer, 0, size);
                }
            } finally {
                if (fos != null) {
                    try {
                        fos.close();
                    } finally {
                        if (is != null) {
                            is.close();
                        }
                    }
                }
            }
        }
    }


    /**
     * 获取文件输入流
     * */
    public static InputStream readFileToInputStream(String path) {
        InputStream inputStream = null;
        try {
            File file = new File(path);
            inputStream = new FileInputStream(file);
        } catch (IOException e) {
            GLog.e(e.getMessage());
        }
        return inputStream;
    }



    /**
     * 根据给出路径自动选择复制文件或整个文件夹
     * @param src :源文件或文件夹路径
     * @param dest :目标文件或文件夹路径
     * */
    public static void copyFiles(String src, String dest) {
        File srcFile = new File(src);
        if (srcFile.exists()) {
            if (srcFile.isFile()) {
                writeFileFromInputStream(readFileToInputStream(src), dest);
            } else {
                File[] subFiles = srcFile.listFiles();
                if (subFiles.length == 0) {
                    File subDir = new File(dest);
                    subDir.mkdirs();
                } else {
                    for (File subFile : subFiles) {
                        String subDirPath = dest + System.getProperty("file.separator") + subFile.getName();
                        copyFiles(subFile.getAbsolutePath(), subDirPath);
                    }
                }
            }
        }
    }




    /**
     * 将文件输入流写入文件
     * */
    public static boolean writeFileFromInputStream(InputStream inStream, String path) {
        boolean result = true;
        try {
            File file = createNewFile(path);
            FileOutputStream out = new FileOutputStream(file);
            byte[] data = new byte[1024];
            int num = 0;
            while ((num = inStream.read(data, 0, data.length)) != -1) {
                out.write(data, 0, num);
            }
            out.close();
            data = null;
        } catch (Exception e) {
            result = false;
            GLog.i( e.getMessage());
        }
        return result;
    }


    /**
     * 文件转换成byte 数组
     * @param filePath   路径
     * @return    byte 数组
     * @throws IOException
     */
    public  static byte[] InputStream2ByteArray(String filePath) throws IOException {

        InputStream in = new FileInputStream(filePath);
        byte[] data = toByteArray(in);
        in.close();

        return data;
    }


    /**
     *  文件流 转换成byte 数组
     * @param in    文件流
     * @return   byte数组
     * @throws IOException
     */
    public static  byte[] toByteArray(InputStream in) throws IOException {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }


    /**
     * 将图片转换成 base64 字符串
     * @param path   文件路径
     * @return
     */
    public static String imageToBase64(String path) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        InputStream is = null;
        byte[] data = null;
        String result = null;
        try {
            is = new FileInputStream(path);
            //创建一个字符流大小的数组。
            data = new byte[is.available()];
            //写入数组
            is.read(data);
            //用默认的编码格式进行编码
            result = Base64.encodeToString(data, Base64.DEFAULT);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return result;
    }


    /**
     * 将图片base64 字符串转换成bitmap
     * @param string  上下文
     * @return
     */
    public static Bitmap base64ToBitmap(String string) {
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray = Base64.decode(string, Base64.DEFAULT);
            bitmap = byteToBitmap(bitmapArray);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;
    }



    private  static Bitmap byteToBitmap(byte[] imgByte) {
        InputStream input = null;
        Bitmap bitmap = null;
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inSampleSize = 1;
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.RGB_565;

        input = new ByteArrayInputStream(imgByte);

        bitmap = BitmapFactory.decodeStream(
                input, null, options);

        if (imgByte != null) {
            imgByte = null;
        }
        try {
            if (input != null) {
                input.close();
                input=null;
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return bitmap;
    }




    /**
     * 创建文件，若文件夹不存在则自动创建文件夹，若文件存在则删除旧文件
     * @param path :待创建文件路径
     * */
    public static File createNewFile(String path) {
        File file = new File(path);
        try {
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if (file.exists()) {
                file.delete();
            }
            file.createNewFile();
        } catch (IOException e) {
            GLog.e(e.getMessage());
        }
        return file;
    }

    /**
     * 递归拷贝Assets下指定文件夹中所有的文件
     *
     * @param context    上下文
     * @param folderName 拷贝的文件夹
     * @param outPath    复制后输出的目录
     */
    public static void copyAssets(Context context, String folderName, String outPath) throws IOException {
        //Assets下指定文件夹(folderName)下所有文件
        String fileNames[] = context.getAssets().list(folderName);
        if (fileNames.length > 0) {
            File file = new File(outPath);
            file.mkdirs();
            for (String fileName : fileNames) {
                copyAssets(context, folderName + File.separator + fileName, outPath + File.separator + fileName);
            }
        } else {

            InputStream is = context.getAssets().open(folderName);
            FileOutputStream fos = new FileOutputStream(new File(outPath));
            byte[] buffer = new byte[1024];
            int byteCount = 0;
            while ((byteCount = is.read(buffer)) != -1) {
                fos.write(buffer, 0, byteCount);
            }
            fos.flush();
            is.close();
            fos.close();
        }
    }

    /**
     * 获取 assets下面的资源文件
     * @param context
     * @param fileName
     * @return
     * @throws IOException
     */
    public static String  getAssetsFileText(Context  context,String fileName) throws IOException {
        InputStreamReader isr = new InputStreamReader(context.getAssets().open(fileName),"UTF-8");
        BufferedReader br = new BufferedReader(isr);
        String line;
        StringBuilder builder = new StringBuilder();
        while((line = br.readLine()) != null){
            builder.append(line);
        }
        br.close();
        isr.close();
        return  builder.toString();
    }


    /**
     * 删除文件 是否保留文件夹
     * @param file
     * @param keep
     */
    public  static  void deleteFile(File file,String keep) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f :files) {
                deleteFile(f,keep);
            }
            file.delete();//如要保留文件夹，只删除文件，请注释这行
        } else if (file.exists()) {
            if(!file.getName().endsWith(keep)) {
                file.delete();
            }
        }
    }


    /**
     * 删除文件及文件夹
     * @param file
     */
    public  static  void deleteFile(File file) {


        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                File f = files[i];
                deleteFile(f);
            }
            file.delete();//如要保留文件夹，只删除文件，请注释这行
        } else if (file.exists()) {
            file.delete();
        }
    }


    /**
     * 删除文件 没有文件夹的情况
     * @param file
     */
    public  static  void deleteFileNotDir(File file) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                File f = files[i];
                deleteFile(f);
            }
//            file.delete();//如要保留文件夹，只删除文件，请注释这行
        } else if (file.exists()) {
            file.delete();
        }
    }





}
